﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplicationTest
{
    public partial class Download : System.Web.UI.Page
    {
        String Dir = "";

        //String serverUrl = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            //serverUrl = Request.Params.Get("HTTP_HOST");
            Label1.Text = Request.Params.Get("HTTP_HOST") + "/uploads/";

            //Label2.Text = HttpContext.Current.Server.ToString();
            //Label1.Text = HttpContext.Current.Server.ToString() + "/uploads/";

            // Create UserTextBox TextBox control.
            TextBox UserTextBox = new TextBox();

            // Configure the UserTextBox TextBox control.
            UserTextBox.ID = "UserTextBox";
            UserTextBox.Columns = 20;


            // Add UserTextBox TextBox control to the Controls collection 
            // of the TextBoxControlPlaceHolder PlaceHolder control.
            TextBoxControlPlaceHolder.Controls.Add(UserTextBox);

            Dir = Request.QueryString["Dir"];
            UserTextBox.Text = Dir == null ? "" : Dir;
        }

        /// <summary>
        /// 初始化文件列表显示
        /// </summary>
        protected void TreeView1_Init(object sender, EventArgs e)
        {
            Dir = Request.QueryString["Dir"];   // 获取参数信息
            
            string dirPath = HttpContext.Current.Server.MapPath("uploads/");
            if (Dir != null && !Dir.Equals("")) dirPath = Dir;

            DirectoryInfo dir = new DirectoryInfo(dirPath);
            TreeNode root = getTreeNode(dir);

            if(root!=null) TreeView1.Nodes.Add(root);
        }

        /// <summary>
        /// 下载选中的文件
        /// </summary>
        protected void Button1_Click(object sender, EventArgs e)
        {
            List<TreeNode> checks = getCheckNodes(TreeView1);
            foreach (TreeNode node in checks)
            {
                downloadFile(node.Value);
                break;
            }
        }


        #region 服务器文件下载相关

        /// <summary>
        /// 从服务器目录文件目录信息，构建TreeNode
        /// </summary>
        private TreeNode getTreeNode(DirectoryInfo dir)
        {
            TreeNode rootNode = null;

            if (dir.Exists)
            {
                rootNode = new TreeNode(dir.Name);

                // 添加子目录节点
                DirectoryInfo[] subDirs = dir.GetDirectories();
                foreach (DirectoryInfo subDir in subDirs)
                {
                    TreeNode child = getTreeNode(subDir);
                    rootNode.ChildNodes.Add(child);
                }

                // 添加子文件节点
                FileInfo[] subFiles = dir.GetFiles();
                foreach (FileInfo subFile in subFiles)
                {
                    TreeNode child = new TreeNode(subFile.Name);
                    child.Value = subFile.FullName;

                    rootNode.ChildNodes.Add(child);
                }
            }

            return rootNode;
        }

        /// <summary>
        /// 获取所有选中的文件
        /// </summary>
        private List<TreeNode> getCheckNodes(TreeView tree)
        {
            List<TreeNode> list = new List<TreeNode>();
            foreach (TreeNode node in tree.Nodes)
            {
                List<TreeNode> subList = getCheckNodes(node);
                list.AddRange(subList);
            }
            return list;
        }

        /// <summary>
        /// 获取所有选中的文件
        /// </summary>
        private List<TreeNode> getCheckNodes(TreeNode node)
        {
            List<TreeNode> list = new List<TreeNode>();
            if (node == null) return list;

            if (node.Checked) list.Add(node);
            foreach (TreeNode child in node.ChildNodes)
            {
                List<TreeNode> subList = getCheckNodes(child);
                list.AddRange(subList);
            }
            return list;
        }

        /// <summary>
        /// 下载服务器目录下的指定文件
        /// </summary>
        private void downloadFile(string filepath)
        {
            try
            {
                ////string DownloadFileName = "~/uploads/" + e.CommandArgument.ToString();//文件路径
                //string DownloadFileName = "~/uploads/styles.xml";//文件路径
                //string filepath = Server.MapPath(DownloadFileName);
                string filename = Path.GetFileName(filepath);
                FileInfo file = new FileInfo(filepath);
                Response.Clear();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
                Response.AddHeader("Content-length", file.Length.ToString());
                Response.Flush();
                Response.WriteFile(filepath);
            }
            catch
            {
                Response.Write("<script>alert('没有找到下载的源文件')</script>");
            }
        }

        # endregion

        /// <summary>
        /// 跳转显示指定目录
        /// </summary>
        protected void Button2_Click(object sender, EventArgs e)
        {
            // Retrieve the UserTextBox TextBox control from the TextBoxControlPlaceHolder
            // PlaceHolder control.
            TextBox TempTextBox = (TextBox)TextBoxControlPlaceHolder.FindControl("UserTextBox");
            String dir = TempTextBox.Text;

            String url = "Download.aspx?Dir=" + dir;
            Response.Redirect(url, false);

            //String url = "Download.aspx?Dir=" + dir;
            //Response.Write("<script language='javascript'>window.location='" + url + "'</script>");

        }

        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {
            //String dir = TextBox1.Text;
        }

    }
}